package goods

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"weekly-exam-1/config"
	"weekly-exam-1/internal/model/dao"
)

type Buy struct {
	Bank     int `form:"bank" json:"bank" xml:"bank"`
	BigSmall int `form:"bigSmall" json:"bigSmall" xml:"bigSmall"`
	BuyType  int `form:"buyType" json:"buyType" xml:"buyType"`
	Looks    int `form:"looks" json:"looks" xml:"looks"`
}

func GoodBuy(c *gin.Context) {
	var json Buy
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var good dao.Goods
	config.DB.Where("bank=? or big_small=? or buy_type=? or looks=?", json.Bank, json.BigSmall, json.BuyType, json.Looks).First(&good)
	if good.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "没有该商品"})
		return
	}
	value, _ := c.Get("userId")
	u := value.(uint)
	if u == good.ID {
		c.JSON(http.StatusBadRequest, gin.H{"error": "本人不允许购买自己的商品"})
		return
	}
	goods := dao.OwnGoods{
		UserId:   int(u),
		Bank:     good.Bank,
		BigSmall: good.BigSmall,
		BuyType:  good.BuyType,
		Looks:    good.Looks,
		Price:    good.Price,
	}
	config.DB.Create(&goods)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "购买成功",
		"data": goods.ID,
	})
	//购买完之后修改闲置表状态
	config.DB.Model(&good).Update("status", 1)
}
